package com.gs.demo.utils;

import com.google.gson.*;

import java.lang.reflect.Type;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class JSONUtil {
    private static final GsonBuilder gsonBuilder = new GsonBuilder().setDateFormat(
        "yyyy-MM-dd HH:mm:ss").registerTypeAdapter(Timestamp.class, new TimestampTypeAdapter()).disableHtmlEscaping();

	private static final Gson gsonStringNull = gsonBuilder.registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory<>()).create();

    /**
     * 将对象转换为json字符串对象
     * 
     * @param object
     * @Description:
     */
    public static String toJson(Object object) {
        return gsonStringNull.toJson(object);
    }

    /**
     * json转对象
     * @param json
     * @param cla
     * @return 
     * @return
     */
    public static <T> T fromJson(String json, Class<T> cla) {
        return gsonStringNull.fromJson(json, cla);
    }

    /**
     * json转对象
     * @param json
     * @param typeOfT
     * @return
     */
    public static <T> T fromJson(String json, Type typeOfT) {
        return gsonStringNull.fromJson(json, typeOfT);
    }

    static final class TimestampTypeAdapter implements JsonSerializer<Timestamp>, JsonDeserializer<Timestamp> {
        @Override
        public JsonElement serialize(Timestamp ts, Type t, JsonSerializationContext jsc) {
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dfString = format.format(new Date(ts.getTime()));
            return new JsonPrimitive(dfString);
        }

        @Override
        public Timestamp deserialize(JsonElement json, Type t, JsonDeserializationContext jsc)
            throws JsonParseException {
            if (!(json instanceof JsonPrimitive)) {
                throw new JsonParseException("时间戳类型错误");
            }

            try {
                DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = format.parse(json.getAsString());
                return new Timestamp(date.getTime());
            } catch (ParseException e) {
                throw new JsonParseException(e);
            }
        }
    }

}
